﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace MulticastTV
{
    /// <summary>
    /// Communication with vlc http server. 
    /// Used for sending vlm broadcast elements to vlc server.
    /// </summary>
    class VlmHttpRequests
    {
       public Socket socket=null;
       public volatile string[] sendreq;
       public volatile string urip =Properties.Settings.Default.VlcIp;
       public volatile int urport = Properties.Settings.Default.VlcPort;
         /// <summary>
        /// Sends array of commands to vlc server.
        /// </summary>
       public void Send()
       {
             setVlm();
       }

       private void setVlm()
       {
           try
           {
               IPAddress ip = IPAddress.Parse(urip);
               socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
               //socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, 1);  //exception in vista
               int port = urport;
               IPEndPoint ipEnd = new IPEndPoint(ip, port);
               socket.ReceiveTimeout = 5000;
               socket.Connect(ipEnd);
           }
           catch { socket = null; return; }

           //set channel
           foreach (string command in sendreq)
           {
               // Send
               try
               {
                   socket.Send(Encoding.ASCII.GetBytes(command));
               }
               catch 
               {
                   if (socket!= null)
                        socket.Close();
                   socket = null;
                   return;
               }
               // Receive the server page.
               Byte[] bytesReceived = new Byte[256];
               int bytes = 0;
               string page = "";
               do
               {
                   try
                   {
                       bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
                   }
                   catch 
                   {
                       break;
                   }
                   page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
                   if (page.EndsWith("</vlm>\n") || page.EndsWith("</vlm>\r\n"))
                   {
                       break;
                   }
               }
               while (bytes > 0);
           }
           
           //close socket
           Dispose();
       }

       public void Dispose()
       { 
            if (socket != null)
           {
               socket.Close();
               socket = null;
           }
       }
   }
}
